//
//  JsMailManager.m
//  CanvasAlpha
//
//  Created by Gikki Ares on 2021/4/12.
//  Copyright © 2021 vgemv. All rights reserved.
//

#import "JsMailManager.h"
#import "JsBase64Manager.h"
#import "JsTimeManager.h"
#import "SKPSMTPMessage.h"
#import "JsDeviceManager.h"

@interface JsMailManager()
<SKPSMTPMessageDelegate>

{
	NSMutableArray * marr_mail;
}

@end

@implementation JsMailManager

static JsMailManager * _sharedInstance;
+ (JsMailManager *)sharedInstance {
	static dispatch_once_t onceToken;
	dispatch_once(&onceToken, ^{
		_sharedInstance = [[JsMailManager alloc] init];
	});
	return _sharedInstance;
}

- (instancetype)init {
	if (self = [super init]) {
		marr_mail = [NSMutableArray array];
	}
	return self;
}

- (void)sendFile:(NSString *)filePath delegate:(id<JsMailManagerDelegate>)d withConfig:(JsMailConfig *)config {
	self.delegte = d;
	[self sendFile:filePath withConfig:config];
}

//邮箱地址:mail.vgemv.com
- (void)sendFile:(NSString *)filePath withConfig:(JsMailConfig *)config {
		// 当前应用版本
	NSDictionary * info = [JsDeviceManager infoDic];
	NSString *appVersion = info[JsDeviceInfoKeyAppVersion];
	NSString *appBuild = info[JsDeviceInfoKeyAppBuild];
	NSString *appFullVersion=[NSString stringWithFormat:@"%@(%@)",appVersion,appBuild];
		// 当前系统版本
	NSString* iOSVersion = info[JsDeviceInfoKeyIosVersion];
	NSString * deviceName = info[JsDeviceInfoKeyDeviceName];
	NSString * deviceModel = info[JsDeviceInfoKeyDeviceModel];
	NSString * content = [NSString stringWithFormat:
						 @"\
						 DeviceModel:%@<br/>\
						 AppVersion:%@<br/>\
						 SystemVersion:%@<br/>\
						  DeviceName:%@<br/>\
						 ",deviceModel,appFullVersion,iOSVersion,deviceName];
	NSString * subject = [NSString stringWithFormat:@"%@操作日志-%@",info[JsDeviceInfoKeyAppName],[JsTimeManager minTimeStringForNow]];
	[self sendMailWithConfig:config subject:subject content:content attachFilePath:filePath emailAttachFileName:nil];

//	47.254.32.24
}


- (void)sendMailWithConfig:(JsMailConfig *)config subject:(NSString *)subject content:(NSString * _Nullable)content attachFilePath:(NSString * _Nullable)filePath emailAttachFileName:(NSString * _Nullable)fileName{
	
	NSString * fromMail = config.fromMail;
	NSString * mailServer = config.mailServer;
	NSString * port = config.mailServerPort;
	NSString * login = config.login;
	NSString * pass = config.pass;
	NSString * toMail = config.toMail;
	
	
	SKPSMTPMessage *mail = [[SKPSMTPMessage alloc] init];
	if(port.length) {
		mail.relayPorts = @[@(port.intValue)];
	}
	mail.fromEmail = fromMail;
	mail.toEmail = toMail;
	mail.login = login;
	mail.pass = pass;
	mail.subject = subject;
	mail.delegate = self;
		//*********************修改SMTP服务器***************
	mail.relayHost = mailServer;
	mail.requiresAuth = YES;
	mail.wantsSecure = YES;
	mail.validateSSLChain = NO;
	[marr_mail addObject:mail];
	
	
	NSMutableArray * marr = [NSMutableArray array];
	
	if(content.length) {
	//文本内容
		//使用网页的方式,排版好看一点.
	NSDictionary *plainPart = [NSDictionary dictionaryWithObjectsAndKeys:@"text/html; charset=UTF-8",kSKPSMTPPartContentTypeKey,
							   content,kSKPSMTPPartMessageKey,@"8bit",kSKPSMTPPartContentTransferEncodingKey,nil];
	
		[marr addObject:plainPart];
	}
	
	
	if(filePath.length) {
	//附件内容
	//邮件中显示的附件名字
	
	
	NSString * attachName = fileName;
	if(!attachName.length) {
		attachName = [filePath lastPathComponent];
	}
		NSString * attachNameBase64 =  [JsBase64Manager base64StringFromString:attachName];
	NSString * emailAttachName = [NSString stringWithFormat:@"\"=?utf-8?B?%@?=\"",attachNameBase64];
		//设置邮件内容
	NSString * disposition = [NSString stringWithFormat:@"attachment; filename=%@",emailAttachName];
		//邮件数据中Content-Type属性.
		NSString * contentType = [NSString stringWithFormat:@"text/plain; name=%@",emailAttachName];
	NSData *data = [NSData dataWithContentsOfFile:filePath];
	NSString *dataBase64String = [JsBase64Manager base64StringFromData:data];
	NSDictionary *logPart =
	@{kSKPSMTPPartContentTypeKey:contentType,
	  kSKPSMTPPartContentTransferEncodingKey:@"base64",
	  kSKPSMTPPartContentDispositionKey:disposition,
	  kSKPSMTPPartMessageKey:dataBase64String
	};
		[marr addObject:logPart];
	}
	if(marr.count) {
		mail.parts = marr;
	}
	dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
		[mail send];
	});
}

-(void)messageSent:(SKPSMTPMessage *)mail{
	NSLog(@"mail send success>>>>>>>");
	if(_delegte && [_delegte respondsToSelector:@selector(jsMailManager:didSendMailSuccess:)]) {
		[_delegte jsMailManager:self didSendMailSuccess:nil];
	}
	[marr_mail removeObject:mail];
}

-(void)messageFailed:(SKPSMTPMessage *)mail error:(NSError *)error{
	NSLog(@"mail send fail,uer info is %@",error.userInfo);
	NSString * info = [NSString stringWithFormat:@"%@",error.userInfo];
	if(_delegte && [_delegte respondsToSelector:@selector(jsMailManager:didSendMailFailed:)]) {
		[_delegte jsMailManager:self didSendMailFailed:info];
	}
	[marr_mail removeObject:mail];
}

@end
